import {sessionStorage} from '../persist'

const app = {
  state: {
    dicts: {},//Map<classname,List<Map<propName,propValue>>>  其中propName等于value和text
    dictsMap: {},//Map<classname,Map<code,label>>
    dictsFull: {},//Map<classname,List<Map<propName,propValue>>>
    dictsKeys: new Set(),//已经加载/正在加载的字典
  },
  mutations: {
    Load_dicts: async (state, dicts) => {
      for (let classname in dicts) {
        let full = dicts[classname];
        let dict = zz.listToList(full, ['code', 'label'], ['value', 'text']);
        Vue.set(state.dicts, classname, dict)//value是枚举项所有字段信息
        Vue.set(state.dictsMap, classname, zz.listToMap(full, 'code', 'label'))
        Vue.set(state.dictsFull, classname, zz.listToMap(full, 'code', null))
      }
    },
    Add_key: async (state, keys) => {
      keys.forEach(k => {
        state.dictsKeys.add(k)
      })
    },
  },
  actions: {
    //刷新字典
    loadDicts: async ({state, commit}, dict_classes) => {
      let map = {}
      let news = dict_classes.filter(c => c && !state.dictsKeys.has(c))
      let dicts = []
      if (noempty(news)) {
        commit('Add_key', news);
        dicts = await zz.post('/common/dicts', news);
        commit('Load_dicts', dicts);
      }
      for (let classname of news) {
        let full = dicts[classname];
        if (full) {
          map[classname] = zz.listToMap(full, 'code', null)
        } else {
          map[classname] = state.dictsFull[classname]
        }
      }
      return map
    },
    closeSideBar({commit}, {withoutAnimation}) {
      commit('CLOSE_SIDEBAR', withoutAnimation)
    },
    toggleDevice({commit}, device) {
      commit('TOGGLE_DEVICE', device)
    }
  }
}

export default app
